package com.gears_software.sxdc.dccx.application;

import android.app.Activity;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.support.multidex.MultiDexApplication;
import android.widget.RemoteViews;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gears_software.sxdc.dccx.data.receiver.NetStateReceiver;
import com.gears_software.sxdc.dccx.data.service.MyPushIntentService;
import com.gears_software.sxdc.dccx.data.sharedPreference.DCCXSp_;
import com.gears_software.sxdc.dccx.ui.activity.LoginActivity;
import com.gears_software.sxdc.dccx.ui.activity.LoginActivity_;
import com.gears_software.sxdc.dccx.ui.util.imagecache.ImageLoadConfig;
import com.github.mzule.activityrouter.router.RouterCallback;
import com.github.mzule.activityrouter.router.RouterCallbackProvider;
import com.github.mzule.activityrouter.router.Routers;
import com.github.mzule.activityrouter.router.SimpleRouterCallback;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechUtility;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.FormatStrategy;
import com.orhanobut.logger.Logger;
import com.orhanobut.logger.PrettyFormatStrategy;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UploadManager;
import com.sdsmdg.tastytoast.TastyToast;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.common.inter.ITagManager;
import com.umeng.message.entity.UMessage;
import com.umeng.message.tag.TagManager;

import org.androidannotations.annotations.EApplication;
import org.androidannotations.annotations.sharedpreferences.Pref;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

import static anet.channel.util.Utils.context;

/**
 * Created by chezhenzhen on 2017/7/17.
 */
@EApplication
public class DCCXApplication extends MultiDexApplication implements RouterCallbackProvider {
    public Typeface iconfont = null;
    public int WARNING;
    public int SUCCESS;
    public int DEFAULT;
    public int INFO;
    public int ERROR;
    public int CONFUSING;
    public int SHORT;
    public int LONG;
    public boolean needLogin = true;
    public int index = 0;//用于记录现在是那个fragment
    public int activityCount = 0;
    @Pref
    DCCXSp_ sp;
    // 重用uploadManager。一般地，只需要创建一个uploadManager对象
    public UploadManager uploadManager;
    PushAgent mPushAgent;
    String[] white = {"login"};
    NetStateReceiver stateReceiver;
    public Date passengerRefreshDate;//记录乘客列表页的刷新时间

    public Date getPassengerRefreshDate() {
        return passengerRefreshDate;
    }

    public void setPassengerRefreshDate(Date passengerRefreshDate) {
        this.passengerRefreshDate = passengerRefreshDate;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        WARNING = TastyToast.WARNING;
        SUCCESS = TastyToast.SUCCESS;
        DEFAULT = TastyToast.DEFAULT;
        INFO = TastyToast.INFO;
        ERROR = TastyToast.ERROR;
        CONFUSING = TastyToast.CONFUSING;
        SHORT = TastyToast.LENGTH_SHORT;
        LONG = TastyToast.LENGTH_LONG;

        iconfont = Typeface.createFromAsset(this.getAssets(), "iconfont/iconfont.ttf");
        //初始化logger
        FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
                .tag("gears")   // (Optional) Global tag for every log. Default PRETTY_LOGGER
                .build();

        Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy));
        //初始化友盟推送
        mPushAgent = PushAgent.getInstance(this);
        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {

            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回device token
                sp.deviceId().put(deviceToken);
                Logger.d("deviceId:" + deviceToken);
            }

            @Override
            public void onFailure(String s, String s1) {
                Logger.d(s + s1);
            }
        });
//        //推送接收后的处理
//        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
//            @Override
//            public void dealWithCustomAction(Context context, UMessage uMessage) {
//                ObjectMapper mapper = new ObjectMapper();
//                String json = uMessage.custom;
//                try {
//                    Map map = mapper.readValue(json, Map.class);
//                    if (map.get("router") != null) {
//                        Routers.open(getApplicationContext(), "gears_dccx://" + map.get("router").toString());
//                    }
//                } catch (IOException ex) {
//                    ex.printStackTrace();
//                }
//                Logger.d(uMessage.custom);
//            }
//        };
//
//        mPushAgent.setNotificationClickHandler(notificationClickHandler);
        mPushAgent.setPushIntentServiceClass(MyPushIntentService.class);

        //七牛初始化
        Configuration config = new Configuration.Builder()
                .chunkSize(512 * 1024)        // 分片上传时，每片的大小。 默认256K
                .putThreshhold(1024 * 1024)   // 启用分片上传阀值。默认512K
                .connectTimeout(10)           // 链接超时。默认10秒
                .useHttps(true)               // 是否使用https上传域名
                .responseTimeout(60)          // 服务器响应超时。默认60秒
                .build();

        uploadManager = new UploadManager(config);
        //fresco初始化
        Fresco.initialize(this, ImageLoadConfig.getInstance(this).getImagePipelineConfig());

        SpeechUtility.createUtility(this, SpeechConstant.APPID + "=59c5000b");

//        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
//            @Override
//            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
//
//            }
//
//            @Override
//            public void onActivityStarted(Activity activity) {
//                activityCount++;
//                if (activityCount == 1) {
//                    //说明从后台回到了前台
//                    Logger.d("回到前台");
//                }
//            }
//
//            @Override
//            public void onActivityResumed(Activity activity) {
//
//            }
//
//            @Override
//            public void onActivityPaused(Activity activity) {
//
//            }
//
//            @Override
//            public void onActivityStopped(Activity activity) {
//                activityCount--;
//                if (activityCount == 0) {
//                    Logger.d("切到后台");
//                }
//            }
//
//            @Override
//            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
//
//            }
//
//            @Override
//            public void onActivityDestroyed(Activity activity) {
//
//            }
//        });

    }

    //路由拦截器
    @Override
    public RouterCallback provideRouterCallback() {

        return new SimpleRouterCallback() {
            @Override
            public boolean beforeOpen(Context context, Uri uri) {
                String str = uri.toString();
                String whiteStr = str.substring("gears_dccx://".length(), str.length());
                for (String item : white) {
                    if (item.equals(whiteStr)) {
                        return false;
                    }
                }
                if (sp.token().get().equals("")) {
                    Intent intent = new Intent(context, LoginActivity_.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                    return true;
                }
                // 是否拦截，true 拦截，false 不拦截
                return false;
            }

            @Override
            public void afterOpen(Context context, Uri uri) {
            }

            @Override
            public void notFound(Context context, Uri uri) {
            }

            @Override
            public void error(Context context, Uri uri, Throwable e) {
            }
        };
    }

    //给添加过车辆的用户添加推送tag
    public void addDriverTag() {
        mPushAgent.getTagManager().add(new TagManager.TCallBack() {
            @Override
            public void onMessage(boolean b, ITagManager.Result result) {

            }
        }, "isDriver");
    }

    public void deleteDriverTag() {
        mPushAgent.getTagManager().delete(new TagManager.TCallBack() {
            @Override
            public void onMessage(boolean b, ITagManager.Result result) {

            }
        }, "isDriver");
    }

    //用户添加别名
    public void addUserAlias(String userId) {
//        mPushAgent.addExclusiveAlias(userId, "DCCX_CP", new UTrack.ICallBack() {
//            @Override
//            public void onMessage(boolean b, String s) {
//                Logger.d(b + s);
//            }
//        });
    }

    //用户删除别名
    public void removeUserAlias(String userId) {
//        mPushAgent.removeAlias(userId, "DCCX_CP", new UTrack.ICallBack() {
//            @Override
//            public void onMessage(boolean b, String s) {
//
//            }
//        });
    }


}
